package core

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"gitee.com/krio/ginc/example/core/lib/conf"
	logger "gitee.com/krio/ginc/example/core/lib/logger/zaplog"
	"gitee.com/krio/ginc/example/util/safe"
)

// StartApiServer 启动api服务
func StartApiServer() {
	apiClient := InitApiRouter()
	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", conf.C.Gin.Port),
		Handler:        apiClient,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	go safe.SafeGo(func() {
		if err := s.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
			logger.Fatalf("start server failed, err: %+v", err)
		}
	})
	if err := closeApiServer(s); err != nil {
		logger.Fatal("server shutdown failed, err: %+v", err)
	}
}

// closeApiServer 优雅关闭api服务
func closeApiServer(s *http.Server) error {
	// 监听中断信号
	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
	i := <-c
	logger.Infof("received signal: %v, server has been shut down", i)

	// 给程序最多3秒时间处理服务的请求
	timeoutCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
	defer cancel()

	return s.Shutdown(timeoutCtx)
}
